/*
 * @Author: your name
 * @Date: 2022-03-19 19:33:41
 * @LastEditTime: 2022-03-27 14:57:01
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \driving\src\article\article.service.ts
 */
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CategoryService } from 'src/category/category.service';
import { CategoryEntity } from 'src/category/entities/category.entity';
import { Repository } from 'typeorm';
import { ArticleInfoDto, ArticlesRo, CreateArticleDto } from './dto/create-article.dto';
import { SelectArticleDto } from './dto/select-article.dto';
import { ArticleEntity } from './entities/article.entity';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(ArticleEntity)
    private readonly postsRepository: Repository<ArticleEntity>,
    private readonly categoryService: CategoryService,
  ) {}

  // 创建文章
  async create(user, post: CreateArticleDto): Promise<number> {
    const { title } = post;
    if (!title) {
      throw new HttpException('缺少文章标题', HttpStatus.BAD_REQUEST);
    }

    const doc = await this.postsRepository.findOne({
      where: { title},
    });
    if (doc) {
      throw new HttpException('文章已存在', HttpStatus.BAD_REQUEST);
    }

    let {  category = 0, status, isRecommend, coverUrl } = post;

    // 根据分类id获取分类
    const categoryDoc = await this.categoryService.findById(category);
    // 根据传入的标签id,如 `1,2`,获取标签
    // const tags = await this.tagService.findByIds(('' + tag).split(','));
    const postParam: Partial<ArticleEntity> = {
      ...post,
      isRecommend: isRecommend ? 1 : 0,
      category: categoryDoc,
      // tags: tags,
      author: user,
    };
    // 判断状态，为publish则设置发布时间
    if (status === 'publish') {
      Object.assign(postParam, {
        publishTime: new Date(),
      });
    }
    const newPost: ArticleEntity = await this.postsRepository.create({
      ...postParam,
    });
    const created = await this.postsRepository.save(newPost);
    return created.id;
  }
  // 分页获取文章
  async getArticle(obj):Promise<ArticlesRo>{
    const qb = await this.postsRepository
      .createQueryBuilder('article')
      .leftJoinAndSelect('article.category','category')
      .leftJoinAndSelect('article.author','user')
      .orderBy('article.count','DESC');
    qb.where('article.content like content and article.title like title and article.category =:category',{title:`%${obj.title}%`,content:`%${obj.content}%`,category:obj.category})
    qb.orderBy('article.count','DESC');
    const Total = await qb.getCount();
    const {pageSize,pageNum} = obj
    qb.limit(pageSize)
    qb.offset(pageSize * (pageNum - 1))
    let articles = await qb.getMany();
    const result:ArticleInfoDto[] = articles.map((item) => item.toResponseObject());
    return {list:result,Total:Total}
  }
  // 获取文章
  async getAllArticle(obj):Promise<ArticlesRo>{
    const qb = await this.postsRepository
      .createQueryBuilder('article')
      .leftJoinAndSelect('article.category','category')
      .leftJoinAndSelect('article.author','user')
      .orderBy('article.count','DESC');
    qb.where('article.content like content and article.title like title and article.category =:category and article.status =:status',{title:`%${obj.title}%`,content:`%${obj.content}%`,category:obj.category,status:'publish'})
    qb.orderBy('article.count','DESC');
    const Total = await qb.getCount();
    let articles = await qb.getMany();
    const result:ArticleInfoDto[] = articles.map((item) => item.toResponseObject());
    return {list:result,Total:Total}
  }
  
  // 获取文章详情
  async getArticleDeail(id):Promise<any>{
    const qb = this.postsRepository
      .createQueryBuilder('article')
      .leftJoinAndSelect('article.author','user')
      .where('article.id=:id')
      .setParameter('id', id);
      const result = await qb.getOne();
      return result
  }

  // 更新文章状态
  async updataStatus(id):Promise<any>{
    const qb = this.postsRepository
      .createQueryBuilder('article')
      .leftJoinAndSelect('article.category', 'category')
      .leftJoinAndSelect('article.author', 'user')
      .where('article.id=:id')
      .setParameter('id', id);
    const result = await qb.getOne();
    await this.postsRepository.update(id, {status: 'publish'})
    return result.toResponseObject();
  }

  // 取消发布
  async cancelStatus(id):Promise<any>{
    const qb = this.postsRepository
      .createQueryBuilder('article')
      .leftJoinAndSelect('article.category', 'category')
      .leftJoinAndSelect('article.author', 'user')
      .where('article.id=:id')
      .setParameter('id', id);

    const result = await qb.getOne();
    await this.postsRepository.update(id, {status: 'draft'})
    return result.toResponseObject();
  }

  // 点赞数加一
  async addNice(id): Promise<any> {
    const qb = this.postsRepository
      .createQueryBuilder('article')
      .leftJoinAndSelect('article.category', 'category')
      .leftJoinAndSelect('article.author', 'user')
      .where('article.id=:id')
      .setParameter('id', id);
    const result = await qb.getOne();
    await this.postsRepository.update(id, {count: result.count+1})
    return result.toResponseObject();
  }
  // 删除文章
  async deleteArticle(id):Promise<any>{
    const article =await this.postsRepository.findOne(id)
    return await this.postsRepository.remove(article)
  }
  // 按userID去搜索文章
  async getByUserID(obj):Promise<ArticlesRo>{
    const qb = this.postsRepository
    .createQueryBuilder('article')
    .orderBy('article.count','DESC')
    .where('article.authorid=:id',{id:obj.id})
    const Total = await qb.getCount();
    const {pageSize,pageNum} = obj
    qb.limit(pageSize)
    qb.offset(pageSize * (pageNum - 1))
    let articles = await qb.getMany();
    const result:ArticleInfoDto[] = articles.map((item) => item.toResponseObject());
    return {list:result,Total:Total}
  }
}